package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;

@Service
@Slf4j
public class CartServiceImpl implements ICartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RemoteProductService remoteProductService;
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        Long userId = SecurityContextHolder.getUserId();
        //大key
        String cartKey = "user:cart" + userId;
        //小key
        String hashKey = skuId.toString();
        BoundHashOperations hashOperations = redisTemplate.boundHashOps(cartKey);
        if (hashOperations.hasKey(hashKey)) {
            //添加过购物车
            CartInfo cartInfo = (CartInfo) hashOperations.get(hashKey);

            int total = cartInfo.getSkuNum() + skuNum;
            int threshHold  = 99;
            cartInfo.setSkuNum(total > threshHold ? threshHold : total);
            hashOperations.put(hashKey,cartInfo);
        }else {
            //首次添加
            //商品种类不能超过50种
            long size = hashOperations.size();
            if (++size > 50){
                throw  new ServiceException("购物车商品种类不能超过50");
            }
            CartInfo cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(1);

            //远程接口调用 根据skuId远程调用商品微服务接口来查询 ProductSku
            R<ProductSku> productSkuR = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (productSkuR.getCode() == HttpStatus.ERROR){//500表示降级处理
                throw new ServiceException(productSkuR.getMsg());
            }
            ProductSku productSku = productSkuR.getData();
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());




            hashOperations.put(hashKey,cartInfo);

        }


    }
}